//
//  EventStatisticsVC.m
//  ConvenientlyTake
//
//  Created by 张奇 on 2022/12/23.
//

#import "EventStatisticsVC.h"
#import "EventStatisticsDisposalCell.h"
#import "ZFPieChart.h"
#import "EventStatisticsAPIRequest.h"
#import "EventStatisticsModel.h"
#import "EventTypeTitleView.h"
#import "TG_Global.h"
#import "EventStatisItemCell.h"
#import "StatisticsKeyValueModel.h"

@interface EventStatisticsVC ()<QMUITableViewDelegate, QMUITableViewDataSource, ZFPieChartDataSource, ZFPieChartDelegate, UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) IBOutlet UIScrollView *bgScrollView;

@property (weak, nonatomic) IBOutlet QMUILabel *dateLabel;
@property (weak, nonatomic) IBOutlet QMUILabel *endDateLabel;

@property (weak, nonatomic) IBOutlet UILabel *departmentLabel;

@property (weak, nonatomic) IBOutlet UICollectionView *staticsCollectionView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *staticsCollectionViewHeight;


@property (strong, nonatomic) IBOutletCollection(UIView) NSArray *statisticsBgView;
@property (weak, nonatomic) IBOutlet UILabel *eventTotalLabel;
@property (weak, nonatomic) IBOutlet UILabel *pendingEventLabel;
@property (weak, nonatomic) IBOutlet UILabel *concludedEventLabel;
@property (weak, nonatomic) IBOutlet UILabel *notHandledEventLabel;
@property (weak, nonatomic) IBOutlet UILabel *assignEventLabel;
@property (weak, nonatomic) IBOutlet UILabel *processEventLabel;
@property (weak, nonatomic) IBOutlet UILabel *toBeingAuditEventLabel;
@property (weak, nonatomic) IBOutlet UILabel *onTimeDisposalRateLabel;

@property (weak, nonatomic) IBOutlet UIView *eventTypeBgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *eventTypeBgViewHeight;

@property (weak, nonatomic) IBOutlet UIView *eventTypeTitlesBgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *eventTypeTitlesBgViewHeight;



@property (weak, nonatomic) IBOutlet QMTableView *eventDisposalRateTableView;
@property (weak, nonatomic) IBOutlet QMTableView *eventDisposalNumTableView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *eventDisposalRateTableViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *eventDisposalNumTableViewHeight;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *eventDisposalRateTableViewMarginBottom;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *eventDisposalNumTableViewMarginBottom;


@property (nonatomic, strong) ZFPieChart *pieChart;
@property (nonatomic, strong) NSArray *eventDisposalRateArray;
@property (nonatomic, strong) NSArray *eventDisposalNumArray;
@property (nonatomic, strong) NSMutableArray <UIColor *> *colorArray;
@property (nonatomic, strong) NSMutableArray <NSString *> *titleArray;
@property (nonatomic, strong) NSMutableArray <NSString *> *numArray;

@property (nonatomic, strong) NSMutableArray *allDepartmentArray;
@property (nonatomic, strong) EventStatisticsModel *eventStaticModel;
@property (nonatomic, copy) NSString *selectCounty, *selectDisposalDeptId;

@property (nonatomic, strong) NSMutableArray *statisDataSource;

@end

@implementation EventStatisticsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"事件统计";
    [self setupUI];
    [self requestData];
}

- (void)setupNavigationItems {
    [super setupNavigationItems];
    [self setNavStyleWhite];
}

- (void)setupUI {

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat width = SCREEN_WIDTH-TableViewSpace*2-10*2;
    
    flowLayout.itemSize = CGSizeMake(width/3.0, width/3.0/110.0*76);
    flowLayout.minimumLineSpacing = 10;
    flowLayout.minimumInteritemSpacing = 8;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.headerReferenceSize = CGSizeZero;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, TableViewSpace, 10, TableViewSpace);
    self.staticsCollectionView.collectionViewLayout = flowLayout;
    
    [self.staticsCollectionView registerNib:[UINib nibWithNibName:@"EventStatisItemCell" bundle:nil] forCellWithReuseIdentifier:@"EventStatisItemCell"];
    
    
    [self.eventTypeBgView addSubview:self.pieChart];
    [self.pieChart mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.eventTypeBgView);
    }];
    
    
    [self.eventDisposalRateTableView registerNib:[UINib nibWithNibName:@"EventStatisticsDisposalCell" bundle:nil] forCellReuseIdentifier:@"EventStatisticsDisposalCell"];
    [self.eventDisposalNumTableView registerNib:[UINib nibWithNibName:@"EventStatisticsDisposalCell" bundle:nil] forCellReuseIdentifier:@"EventStatisticsDisposalCell"];
    
    self.eventTypeBgViewHeight.constant = 0;
    //    self.eventTypeTitlesBgViewHeight.constant = 0;
    
    //默认当月1号~当天
    self.dateLabel.text = [NSString stringWithFormat:@"%zd-%.2ld-01",[NSDate date].year, (long)[NSDate date].month];
    self.endDateLabel.text = [[NSDate date] getDateStringYMD];
    
    WEAK
    [self.bgScrollView addLegendHeaderWithRefreshingBlock:^{
        STRONG
        [self requestData];
    }];
}


- (void)requestData {
    [TGProgressHUD showHUD:nil];
    [EventStatisticsAPIRequest GETGetEventStatisticsWithStartDate:R(self.dateLabel.text) endDate:R(self.endDateLabel.text) county:R(self.selectCounty) disposalDeptId:R(self.selectDisposalDeptId) success:^(TGResponseItem *responseItem) {
        [TGProgressHUD dismissMPHUD];
        if (responseItem.success) {
            
            self.eventStaticModel = [EventStatisticsModel modelWithJSON:responseItem.data];
            
            [self configureData];
            [self.bgScrollView endPullDown];
        }
    } fail:^(NSError *error) {
        
    }];
    
}

- (void)configureData {
    EventMainStatisticsVo *staticsModel = self.eventStaticModel.eventMainStatisticsVo;
//    self.eventTotalLabel.text = R(staticsModel.eventTotal);
//    self.pendingEventLabel.text = R(staticsModel.pendingEvent);
//    self.concludedEventLabel.text = R(staticsModel.concludedEvent);
//    self.notHandledEventLabel.text = R(staticsModel.notHandledEvent);
//    self.assignEventLabel.text = R(staticsModel.assignEvent);
//    self.processEventLabel.text = R(staticsModel.processEvent);
//    self.toBeingAuditEventLabel.text = R(staticsModel.toBeingAuditEvent);
//    self.onTimeDisposalRateLabel.text = R(staticsModel.onTimeDisposalRate);
    
    self.statisDataSource = [NSMutableArray array];
    CGFloat width = SCREEN_WIDTH-TableViewSpace*2-10*2;
    
    if (staticsModel.showStatus) {
        NSArray *nameArray= @[@"事件总数", @"待受理", @"已办结", @"不予受理", @"指派中", @"处理中", @"审核中", @"按时处置率"];
        NSArray *numArray= @[staticsModel.eventTotal?:@"0", staticsModel.pendingEvent?:@"0", staticsModel.concludedEvent?:@"0", staticsModel.notHandledEvent?:@"0", staticsModel.assignEvent?:@"0", staticsModel.processEvent?:@"0", staticsModel.toBeingAuditEvent?:@"0", staticsModel.onTimeDisposalRate?:@"0"];
        for (int i = 0; i < nameArray.count; i++) {
            StatisticsKeyValueModel *tempModel = [[StatisticsKeyValueModel alloc] init];
            tempModel.eventName = R(nameArray[i]);
            tempModel.eventNum = R(numArray[i]);
            [self.statisDataSource addObject:tempModel];
        }
        self.staticsCollectionViewHeight.constant = width/3.0/110.0*76*3+10*2+15;
    } else {
        NSArray *nameArray= @[@"事件总数", @"已办结", @"指派中", @"处理中", @"审核中", @"按时处置率"];
        NSArray *numArray= @[staticsModel.eventTotal?:@"0", staticsModel.concludedEvent?:@"0", staticsModel.assignEvent?:@"0", staticsModel.processEvent?:@"0", staticsModel.toBeingAuditEvent?:@"0", staticsModel.onTimeDisposalRate?:@"0"];
        for (int i = 0; i < nameArray.count; i++) {
            StatisticsKeyValueModel *tempModel = [[StatisticsKeyValueModel alloc] init];
            tempModel.eventName = R(nameArray[i]);
            tempModel.eventNum = R(numArray[i]);
            [self.statisDataSource addObject:tempModel];
        }
        self.staticsCollectionViewHeight.constant = width/3.0/110.0*76*2+10*2+5;
    }
    
    [self.staticsCollectionView reloadData];
    
    self.colorArray = [NSMutableArray array];
    self.titleArray = [NSMutableArray array];
    self.numArray = [NSMutableArray array];
    NSInteger allNum = 0;
    for (EventTypeStatisticsVo *tempModel in self.eventStaticModel.eventTypeStatisticsVoList) {
        if (![tempModel.eventType isEqualToString:@"-1"]) {
            [self.colorArray addObject:[UIColor randomColor]];
            [self.titleArray addObject:R(tempModel.eventTypeName)];
            [self.numArray addObject:R(tempModel.eventNum)];
            allNum += tempModel.eventNum.integerValue;
        }
    }
    
//    self.colorArray = [NSMutableArray arrayWithArray:@[UIColorRed, UIColorGreen, UIColorBlue, [UIColor cyanColor]]];
//    self.titleArray = [NSMutableArray arrayWithArray:@[@"乱贴乱画", @"小摊小贩乱摆摊", @"公共设施损毁报修", @"公共设施损毁报修"]];
//    self.numArray = [NSMutableArray arrayWithArray:@[@"1", @"2", @"3", @"4"]];
    if (allNum == 0) {
        self.eventTypeBgViewHeight.constant = 0;
    } else {
        self.eventTypeBgViewHeight.constant = 140;
    }
    if (self.colorArray.count == 0) {
        self.eventTypeTitlesBgView.hidden = YES;
        self.eventTypeTitlesBgViewHeight.constant = 0;
    } else {
        self.eventTypeTitlesBgView.hidden = NO;
        
        [self.eventTypeTitlesBgView removeAllSubviews];
        CGFloat titleViewHeight = 25;
        CGFloat titleViewWidth = SCREEN_WIDTH/2.0-15;
        self.eventTypeTitlesBgViewHeight.constant = 30 + titleViewHeight*ceil(self.colorArray.count/2.0);
        
        for (int i = 0; i < self.colorArray.count; i++) {
            EventTypeTitleView *titleView = [[EventTypeTitleView alloc] initWithColor:self.colorArray[i] title:self.titleArray[i] eventNum:self.numArray[i]];
            [self.eventTypeTitlesBgView addSubview:titleView];
            
            [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(i%2 ? titleViewWidth: 0);
                make.top.mas_equalTo(i/2*titleViewHeight+15);
                make.width.mas_equalTo(titleViewWidth);
                make.height.mas_equalTo(titleViewHeight);
            }];
        }
        
    }
    [self.pieChart strokePath];
    
    
        self.eventDisposalRateArray = self.eventStaticModel.eventDisposalRateVoList;
        self.eventDisposalNumArray = self.eventStaticModel.eventDisposalVoList;
//    self.eventDisposalRateArray = @[@"", @"", @"", @"", @"", @""];
//    self.eventDisposalNumArray = @[@"", @"", @"", @"", @"", @""];
    
    self.eventDisposalRateTableViewHeight.constant = self.eventDisposalRateArray.count*45;
    self.eventDisposalRateTableViewMarginBottom.constant = self.eventDisposalRateArray.count>0 ? 15: 5;
    self.eventDisposalNumTableViewHeight.constant = self.eventDisposalNumArray.count*45;
    self.eventDisposalNumTableViewMarginBottom.constant = self.eventDisposalNumArray.count>0 ? 15: 5;
    [self.eventDisposalRateTableView reloadData];
    [self.eventDisposalNumTableView reloadData];
    
}
//返回value数据(NSArray必须存储NSString类型)
- (NSArray *)valueArrayInPieChart:(ZFPieChart *)chart {
    return self.numArray;
}


//返回颜色数组(NSArray必须存储UIColor类型)
- (NSArray *)colorArrayInPieChart:(ZFPieChart *)chart {
    return self.colorArray;
}

//设置饼图的半径
- (CGFloat)radiusInPieChart:(ZFPieChart *)pieChart {
    return 70;
}

- (CGFloat)radiusAverageNumberOfSegments:(ZFPieChart *)pieChart {
    return 5;
}

- (IBAction)clickChooseDate:(UIButton *)sender {
    [self showBeginDatePicker];
}


- (IBAction)clickChooseEndDate:(UIButton *)sender {
    [self showBeginDatePicker];
}

- (void)showBeginDatePicker {
    LDDatePickerView *picker = [[LDDatePickerView alloc] init];
    picker.datePickerMode = PGDatePickerModeDate;
    picker.middleTextStr = @"请选择开始时间";
    picker.minimumDate = [NSDate dateWithdateSr:@"2023-01-01" format:@"yyyy-MM-dd"];
    picker.maximumDate = [NSDate dateWithdateSr:R(self.endDateLabel.text) format:@"yyyy-MM-dd"];
    
    picker.currentDate = [NSDate dateWithdateSr:R(self.dateLabel.text) format:@"yyyy-MM-dd"];
    WEAK
    [picker setDidSelectComplent:^(NSString * _Nullable dateString) {
        STRONG
        NSLog(@"---%@---", dateString);
//        self.dateLabel.text = dateString;
//        [self requestData];
        [self showEndDatePickerWithBeginStr:dateString];
    }];
    [picker show];
}

- (void)showEndDatePickerWithBeginStr:(NSString *)beginStr {
    LDDatePickerView *picker = [[LDDatePickerView alloc] init];
    picker.datePickerMode = PGDatePickerModeDate;
    picker.middleTextStr = @"请选择结束时间";
    picker.minimumDate = [NSDate dateWithdateSr:R(self.dateLabel.text) format:@"yyyy-MM-dd"];
    picker.maximumDate = [NSDate date];
    
    picker.currentDate = [NSDate dateWithdateSr:R(self.endDateLabel.text) format:@"yyyy-MM-dd"];
    WEAK
    [picker setDidSelectComplent:^(NSString * _Nullable dateString) {
        STRONG
        NSLog(@"---%@---", dateString);
        self.dateLabel.text = beginStr;
        self.endDateLabel.text = dateString;
        [self requestData];
    }];
    [picker show];
}

- (IBAction)clickChooseDepartment:(UIButton *)sender {
    
    if (self.allDepartmentArray.count > 0) {
        [self showDepartmentPicker];
    } else {
        [TG_Global getEnabledDepartmentArrayWithComplemention:^(NSArray <LDPickerItem *> *dataSource) {
            self.allDepartmentArray = [NSMutableArray arrayWithArray:dataSource];
            [self showDepartmentPicker];
        }];
    }
    
}

- (void)showDepartmentPicker {
    if (self.allDepartmentArray.count == 0) {return;}
    LDAddressPickerView * picker = [[LDAddressPickerView alloc] initWithDepartmentData:self.allDepartmentArray compantsCount:2];
    WEAK
    [picker didSelectedHandler:^(NSArray<LDPickerItem *> *objs, NSString *dsc) {
        NSLog(@"%@\n%@", objs, dsc);
        NSArray *array = [dsc componentsSeparatedByString:@"·"];
        NSString *firstResult = [array firstObject];
        NSString *lastResult = [array lastObject];
        STRONG
//      self.departmentLabel.text = [array componentsJoinedByString:@"-"];
        self.departmentLabel.text = lastResult;
        if ([firstResult isEqualToString:@"全部"]) {
            self.selectCounty = nil;
            self.selectDisposalDeptId = nil;
            self.departmentLabel.text = @"全部";
        } else if ([lastResult containsString:@"全部"] || [lastResult isEqualToString:@"-"]) {
            self.selectCounty = objs.firstObject.obj;
            self.selectDisposalDeptId = nil;
            self.departmentLabel.text = @"全部部门";
        } else {
            self.selectCounty = objs.firstObject.obj;
            self.selectDisposalDeptId = objs.lastObject.obj;
        }
        [self requestData];
        
    }];
    [picker show];
    
}

#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.statisDataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    EventStatisItemCell *cell = (EventStatisItemCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"EventStatisItemCell" forIndexPath:indexPath];
    StatisticsKeyValueModel *model = self.statisDataSource[indexPath.item];
    cell.model = model;
    return cell;
}

#pragma mark - QMUITableViewDelegate, QMUITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([tableView isEqual:self.eventDisposalRateTableView]) {
        return self.eventDisposalRateArray.count;
    } else if ([tableView isEqual:self.eventDisposalNumTableView]) {
        return self.eventDisposalNumArray.count;
    } else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EventStatisticsDisposalCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EventStatisticsDisposalCell"];
    cell.row = indexPath.row;
    if ([tableView isEqual:self.eventDisposalRateTableView]) {
        cell.rateModel = self.eventDisposalRateArray[indexPath.row];
    } else {
        cell.disposalModel = self.eventDisposalNumArray[indexPath.row];
    }
    return cell;
}

- (ZFPieChart *)pieChart {
    if (!_pieChart) {
        _pieChart = [[ZFPieChart alloc] init];
        _pieChart.dataSource = self;
        _pieChart.delegate = self;
        _pieChart.isShadow = NO;
        _pieChart.isShowPercent = NO;
        _pieChart.isAnimated = NO;
    }
    return _pieChart;
}

- (NSMutableArray *)statisDataSource {
    if (!_statisDataSource) {
        _statisDataSource = [NSMutableArray array];
    }
    return _statisDataSource;
}

@end
